package com.rainng.coursesystem.manager.admin;

import com.rainng.coursesystem.dao.EventDAO;
import com.rainng.coursesystem.dao.MemberEventDAO;
import com.rainng.coursesystem.dao.MemberDAO;
import com.rainng.coursesystem.manager.BaseManager;
import com.rainng.coursesystem.model.entity.EventEntity;
import com.rainng.coursesystem.model.entity.MemberEventEntity;
import com.rainng.coursesystem.model.entity.MemberEntity;
import com.rainng.coursesystem.model.vo.response.table.MemberEventItemVO;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class MemberEventManager extends BaseManager {
    private final EventDAO eventDAO;
    private final MemberEventDAO memberEventDAO;
    private final MemberDAO memberDAO;

    public MemberEventManager(EventDAO eventDAO, MemberEventDAO memberEventDAO, MemberDAO memberDAO) {
        this.eventDAO = eventDAO;
        this.memberEventDAO = memberEventDAO;
        this.memberDAO = memberDAO;
    }

    public Integer getPageCount(String teamName, String eventName, String memberName) {
        int count = memberEventDAO.count(teamName, eventName, memberName);
        return calcPageCount(count, MemberEventDAO.PAGE_SIZE);
    }

    public List<MemberEventItemVO> getPage(Integer index, String teamName, String eventName, String memberName) {
        return memberEventDAO.getPage(index, teamName, eventName, memberName);
    }

    public MemberEventEntity get(Integer id) {
        return memberEventDAO.get(id);
    }

    @Transactional
    public int create(MemberEventEntity entity) {
        eventDAO.increaseSelectedCount(entity.getEventId());
        return memberEventDAO.insert(entity);
    }

    public int update(MemberEventEntity entity) {
        return memberEventDAO.update(entity);
    }

    @Transactional
    public int delete(MemberEventEntity entity) {
        eventDAO.decreaseSelectedCount(entity.getEventId());
        return memberEventDAO.delete(entity.getId());
    }

    public EventEntity getEventById(Integer eventId) {
        return eventDAO.get(eventId);
    }

    public MemberEntity getMemberById(Integer memberId) {
        return memberDAO.get(memberId);
    }

    public MemberEventEntity getByEventIdAndMemberId(Integer eventId, Integer memberId) {
        return memberEventDAO.getByEventIdAndMemberId(eventId, memberId);
    }

    public Integer getMemberBudgetById(Integer memberId) {
        return memberDAO.getBudgetById(memberId);
    }

    public boolean inSameArea(Integer eventId, Integer memberId) {
        return eventDAO.getAreaIdById(eventId)
                .equals(memberDAO.getAreaIdById(memberId));
    }
}
